<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <sticky :z-index="10" :class-name="'sub-navbar '">
        <el-button
          v-loading="loading"
          style="margin-left: 10px"
          type="success"
          @click="submitForm"
        >
          发布
        </el-button>
        <el-button
          v-if="$route.path !== '/nested/banner/createBanner'"
          type="primary"
          @click="$router.go(-1)"
          class="btn-back"
          >返回</el-button
        >
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <!-- <el-col :span="24">
            <el-form-item style="margin-bottom: 40px" prop="title">
              <MDinput
                v-model="postForm.title"
                :maxlength="100"
                name="name"
                required
              >
                Title
              </MDinput>
            </el-form-item>
          </el-col> -->
          <!-- <el-col>
            <el-tooltip :content="'Status: ' + postForm.status" placement="top">
              <el-switch
                v-model="postForm.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="2"
                inactive-text="禁用"
                active-text="启用"
                style="margin-bottom: 40px"
                @change="switchStatus"
              >
              </el-switch>
            </el-tooltip>
          </el-col> -->
          <el-col>
            <el-form-item
              label-width="90px"
              label="Importance:"
              class="postInfo-container-item"
              @change="rateChange"
            >
              <el-rate
                v-model="postForm.play"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                :low-threshold="1"
                :high-threshold="5"
                style="display: inline-block"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item prop="content" style="margin-bottom: 30px">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item> -->

        <el-form-item prop="cover" style="margin-bottom: 30px">
          <Upload v-model="postForm.cover" :update="isEdit" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import Upload from "@/components/Upload/uploadImage.vue";
import MDinput from "@/components/MDinput";
import Sticky from "@/components/Sticky"; // 粘性header组件
import { fetchArticle, updateArticle, createArticle } from "@/api/article";
import { searchUser } from "@/api/remote-search";
import { checkPermission } from "@/utils/hasPermission";
const defaultForm = {
  // title: "", // 文章题目
  // content: "", // 文章内容
  cover: "", // 文章图片
  play: 1,
  status: 1,
  id: undefined,
};

export default {
  name: "ArticleDetail",
  components: {
    Tinymce,
    MDinput,
    Upload,
    Sticky,
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        this.$message({
          message: rule.field + "为必传项",
          type: "error",
        });
        callback(new Error(rule.field + "为必传项"));
      } else {
        callback();
      }
    };
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        cover: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
      },
      tempRoute: {},
      coverList: [],
      rawData: {},
      diffData: "",
    };
  },
  watch: {
    "postForm.status"(val) {
      console.log(val);
    },
    "postForm.play"(val) {
      console.log(val);
    },
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
    this.tempRoute = Object.assign({}, this.$route);
  },
  methods: {
    checkPermission,
    fetchData(id) {
      fetchArticle(id)
        .then((response) => {
          this.postForm = response.result[0];
          this.rawData = { ...response.result[0] };
          console.log(response.result[0]);

          // set tagsview title
          this.setTagsViewTitle();

          // set page title
          this.setPageTitle();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    setTagsViewTitle() {
      const title = "Edit Article";
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.id}`,
      });
      // this.$store.dispatch("tagsView/updateVisitedView", route);
    },
    setPageTitle() {
      const title = "Edit Article";
      document.title = `${title} - ${this.postForm.id}`;
    },
    submitForm() {
      if (!this.checkPermission()) return;
      console.log(this.postForm);
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (!this.isEdit) {
            let data = this.postForm;
            delete data["id"];
            console.log(data);
            createArticle(data).then((res) => {
              this.$notify({
                title: "成功",
                message: "发布文章成功",
                type: "success",
                duration: 2000,
              });
            });
          } else {
            // let data = this.postForm;
            // delete data["create_time"];
            this.diffFormData();
            if (!this.diffData) {
              this.$message.error("未修改数据，无需提交！");
            } else {
              console.log(this.diffData);
              this.diffData.id = this.postForm.id;
              this.diffData.status = this.postForm.status;
              updateArticle(this.diffData).then((res) => {
                if (res.code !== 1) {
                  return this.$notify({
                    title: "失败",
                    message: "更新文章失败",
                    type: "error",
                    duration: 2000,
                  });
                }
                this.$notify({
                  title: "成功",
                  message: "更新文章成功",
                  type: "success",
                  duration: 2000,
                });
                console.log(res);
              });
              this.$router.go(-1);
            }
            this.loading = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getRemoteUserList(query) {
      searchUser(query).then((response) => {
        if (!response.data.items) return;
        this.userListOptions = response.data.items.map((v) => v.name);
      });
    },
    // switchStatus(val) {
    //   // console.log(val);
    //   this.postForm.status = val;
    // },
    rateChange(val) {
      console.log(val);
      this.postForm.play = val;
    },
    // 判断数据是否更新
    diffFormData() {
      for (let k in this.rawData) {
        if (this.rawData[k] !== this.postForm[k]) {
          if (!this.diffData) {
            this.diffData = {};
          }
          this.diffData[k] = this.postForm[k];
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
